<template>
  <PageWrapper class="high-form" :title="getTitle">
    <CollapseContainer title="基础信息">
      <BasicForm @register="registerForm" ref="formRef">

        <template #remoteSearchPlan="{ model, field }">
          <ApiSelect :api="getAllPlan" multiple showSearch v-model:value="model[field]" :filterOption="true"
            resultField="data" labelField="formNo" valueField="id" :params="searchParams2" />
        </template>

      </BasicForm>

    </CollapseContainer>
    <CollapseContainer title="流程信息">
      <!-- 审批信息 -->
      <SelectApprover :id="id" :type="type" @success="getFlowData" />
    </CollapseContainer>
    <a-button type="primary" @click="handleSubmitForm" v-if="serverData.showCommit"> 提交 </a-button> <span> </span>
    <a-button type="primary" @click="handleSaveForm(0)" v-if="serverData.showCommit"> 存草稿 </a-button> <span> </span>
    <a-button color="error" @click="handleDeleteForm" v-if="serverData.showCommit && id > 0"> 删除 </a-button>

  </PageWrapper>
</template>

<script lang="ts">
import { defineComponent, ref, onBeforeMount, onMounted, computed, unref, } from 'vue';
import { Button, Tag, List } from 'ant-design-vue';
import { BasicForm, useForm, ApiSelect } from '/@/components/Form/index';
import { CollapseContainer } from '/@/components/Container';
import { useMessage } from '/@/hooks/web/useMessage';
import { useRoute, useRouter } from 'vue-router'
import { PageWrapper } from '/@/components/Page';
import { BasicUpload } from '/@/components/Upload';

import SelectApprover from '/@/views/process/SelectApprover.vue';
import { useDebounceFn } from '@vueuse/core';
import { useUserStore } from '/@/store/modules/user';

import { FormSchema } from '/@/components/Table';
import { uploadApi } from '/@/api/sys/upload';
import { ProjectTypeList } from '/@/api/base/dictionary';
import { getCompanies } from '/@/api/org/company';
import { getAll as getAllReason } from '/@/api/project/reason';
import { getAll as getAllPlan } from '/@/api/project/plan';
import { getAll as getAllClient, view as viewClient } from '/@/api/business/client';
import { getAllList } from '/@/api/privilege/account';
import { add, update, del } from '/@/api/business/contract';
import { businessdata } from '/@/api/work/work';


export default defineComponent({
  components: {
    BasicUpload, BasicForm, CollapseContainer, PageWrapper, Button, Tag, ApiSelect, SelectApprover,
    List, ListItem: List.Item, ListItemMeta: List.Item.Meta,
  },
  setup() {

    //表单字段定义
    const formSchema: FormSchema[] = [
      {
        field: 'id',
        label: 'ID',
        component: 'Input',
        show: false,
      },
      {
        field: 'formNo',
        label: '合同编号',
        component: 'Input',
        componentProps: {
          disabled: true,
        },
      },
      {
        field: 'clientId',
        label: '委托单位',
        component: 'ApiSelect',
        componentProps: {
          api: getAllClient,
          showSearch: true,
          optionFilterProp: 'label',
          resultField: 'data',
          labelField: 'name',
          valueField: 'id',
          onChange: (value) => {
            console.log('1.委托单位变更:', value);
            handleSelectChange(value)
          },
        },
        required: true,
      },
      {
        field: 'projectType',
        label: '委托业务',
        component: 'Input',
        show: false,
      },
      {
        field: 'projectTypeList',
        label: '委托业务',
        component: 'ApiSelect',
        required: true,
        componentProps: {
          api: ProjectTypeList,
          showSearch: true,
          optionFilterProp: 'label',
          mode: "multiple",
          resultField: 'value',
          labelField: 'value',
          valueField: 'value',
          onChange: (e) => {
            batchAdd(e);
          },
        },
      },
      {
        field: 'clientManager',
        label: '联系人及电话',
        component: 'Select',
        colProps: { span: 24 },
      },
      {
        field: 'clientAddress',
        label: '地址',
        component: 'Select',
        colProps: { span: 24 },
      },
      {
        field: 'companyId',
        label: '我方单位名称',
        required: true,
        component: 'ApiSelect',
        componentProps: {
          api: getCompanies,
          showSearch: true,
          optionFilterProp: 'label',
          resultField: 'data',
          labelField: 'cname',
          valueField: 'id',
        },
      },
      {
        field: 'projectOperator',
        label: '项目经办人',
        colProps: { span: 24 },
        required: true,
        component: 'ApiSelect',
        componentProps: {
          disabled: true,
          api: getAllList,
          params: {},
          labelField: 'realName',
          valueField: 'id',
        }
      },

      {
        field: 'projectManager',
        label: '项目负责人',
        component: 'ApiSelect',
        componentProps: {
          api: getAllList,
          showSearch: true,
          optionFilterProp: 'label',
          params: {},
          labelField: 'realName',
          valueField: 'id',
        },
        colProps: { span: 24 },
      },

      {
        field: 'contractBegin',
        label: '合同开始时间',
        required: true,
        component: 'DatePicker',
        colProps: { span: 24 },
      },
      {
        field: 'contractEnd',
        label: '合同结束时间',
        required: true,
        component: 'DatePicker',
        colProps: { span: 24 },
      },
      {
        field: 'finishTime',
        label: '计划完成时间',
        component: 'DatePicker',
        colProps: { span: 24 },
      },
      {
        field: 'onlineContractList',
        label: '线上合同',
        component: 'Upload',
        colProps: { span: 24 },
        componentProps: {
          api: uploadApi,
        },
      },

      {
        field: 'contractAmount',
        label: '合同金额',
        component: 'Input',
        colProps: { span: 24 },
        slot: 'amountList',
        helpMessage: ['表单提交时自动检测合同总金额是否等于线上合同的总金额，委托业务只有一类时时自动调用线上合同数据'],
      },
      {
        field: 'contractRatio',
        label: '派工到账比例',
        component: 'Input',
        colProps: { span: 24 },
        slot: 'ratioList',
        helpMessage: ['默认100%'],
      },
      {
        field: 'checkReason',
        label: '委托依据',
        component: 'ApiSelect',
        componentProps: {
          showSearch: true,
          optionFilterProp: 'label',
          //resultField: 'data',
          labelField: 'detail',
          valueField: 'id',
        },
        helpMessage: ['输入检测依据编号，模糊匹配检测依据'],
      },
      {
        field: 'checkPlan',
        label: '采样计划',
        component: 'ApiSelect',
        componentProps: {
          showSearch: true,
          optionFilterProp: 'label',
          resultField: 'data',
          labelField: 'formNo',
          valueField: 'id',
        },
        helpMessage: ['输入采样计划编号，模糊匹配采样计划'],
        //slot: 'remoteSearchPlan',
      },
      
      {
        field: 'fileList',
        label: '附件',
        component: 'Upload',
        colProps: { span: 24 },
        componentProps: {
          api: uploadApi,
        },
      },
      {
        field: 'remark1',
        label: '备注',
        component: 'InputTextArea',
      },
    ];

    // 委托单位变更事件
    const handleSelectChange = (clientId) => {
      setFieldsValue({ 'receivedId': '' })
      setFieldsValue({ 'receiptCompany': '' })
      //联系人电话地址
      viewClient(clientId).then(res => {
        updateSchema({
          field: 'clientManager',
          componentProps: {
            options: [],
          },
        });
        updateSchema({
          field: 'clientManager',
          componentProps: {
            options: res.managerList.map(item => ({ label: item.name + item.tel, value: item.name + item.tel })),
          }
        });
        updateSchema({
          field: 'clientAddress',
          componentProps: {
            options: [],
          },
        });
        updateSchema({
          field: 'clientAddress',
          componentProps: {
            options: res.addressList.map(item => ({ label: item.name, value: item.name })),
          }
        });
        console.log('2.获取联系人电话地址成功', res);
      });
      //委托依据
      updateSchema({
        field: 'checkReason',
        component: 'ApiSelect',
        componentProps: {
          api: getAllReason,
          params: { clientId: clientId },
          labelField: 'detail',
          valueField: 'id',
        }
      })
      //采样计划
      updateSchema({
        field: 'checkPlan',
        component: 'ApiSelect',
        componentProps: {
          api: getAllPlan,
          params: { clientId: clientId },
          labelField: 'detail',
          valueField: 'id',
        }
      })



      //handleSelectChange end
    }


    //主表单
    const [registerForm, { appendSchemaByField, removeSchemaByField, updateSchema, setFieldsValue, validate }] = useForm({
      schemas: formSchema,
      labelWidth: 150,
      showActionButtonGroup: false,
    });
    const id = ref(0);
    const type = ref('BusinessContract');

    const selectedTypeList: any = ref([]); // 选择的委托业务列表

    const serverDataType: any = { showApprove: false, aaList: [], ccList: [] }
    const serverData = ref(serverDataType);
    const isUpdate = ref(false);
    const getTitle = computed(() => (!unref(isUpdate) ? '新增合同' : '编辑合同'));
    const { createMessage } = useMessage();
    const router = useRouter();

    //采样计划搜索begin
    const keyword2 = ref<string>('');
    const searchParams2 = computed<Recordable>(() => {
      return { keyword: unref(keyword2) };
    });
    function onSearch2(value: string) {
      keyword2.value = value;
    }
    //采样计划搜索end

    onBeforeMount(() => {
      // 获取路由参数
      const r = useRoute();
      let idStr = r.params.id
      if (typeof (idStr) == 'string') {
        id.value = parseInt(idStr, 10)
      } else {
        id.value = parseInt(idStr[0], 10)
      }
      console.log(`1.父页面onBeforeMount, 通过props向子页面传递数据`, id.value)
    })

    const userStore = useUserStore();
    onMounted(() => {
      // 固定项目经办人为当前账号
      const userId = userStore.getUserInfo.id;
      setFieldsValue({
        projectOperator: userId,
      });
      if (id.value > 0) {
        isUpdate.value = true
        setFieldsValue(serverData)
        businessdata({ id: id.value, type: type.value, index: 0 }).then(res => {
          handleSelectChange(res.clientId)
          //增加表单字段
          batchAdd(res.projectTypeList)
          //数据加工
          if (res.contractAmount == null) {
            res.contractAmount = []
          } else {
            res.contractAmount = JSON.parse(res.contractAmount)
          }
          if (res.contractRatio == null) {
            res.contractRatio = []
          } else {
            res.contractRatio = JSON.parse(res.contractRatio)
          }
          res.contractAmount.forEach((item) => {
            res[item.code] = item.value
          });
          res.contractRatio.forEach((item) => {
            res[item.code] = item.value
          });
          setFieldsValue(res)
          console.log('获取后台合同数据成功', res)

        })
      }
      //console.log(`1.父页面onMounted, 通过setFieldsValue表单赋值`, serverData.value)
    })


    // 从子页面获取表单数据
    function getFlowData(returnData: any) {
      serverData.value = returnData
    }

    //提交，需要选择审批人
    async function handleSubmitForm() {
      if (serverData.value.aaList == null || serverData.value.aaList.length == 0) {
        createMessage.success({
          content: '请选择审批人',
          duration: 1,
        });
        return
      }
      await handleSaveForm(1)
      router.push('/work/work-done');//跳转已处理
    }
    //存草稿
    async function handleSaveForm(type) {
      let content = '存草稿成功'
      const values = await validate();
      values.projectType = values.projectTypeList.join(',');
      let contractAmount: any[] = [], contractRatio: any[] = [];
      console.log('selectedTypeList=', selectedTypeList)
      values.projectTypeList.forEach((item, index) => {
        contractAmount.push({ name: item, code: 'contractAmount' + index, value: values['contractAmount' + index] });
        contractRatio.push({ name: item, code: 'contractRatio' + index, value: values['contractRatio' + index] });
      });
      values.contractAmount = JSON.stringify(contractAmount);
      values.contractRatio = JSON.stringify(contractRatio);

      if (type === 1) {
        content = '提交成功'
        values['aaList'] = serverData.value.aaList
        values['ccList'] = serverData.value.ccList
      }
      console.log('formData=', values)

      if (unref(isUpdate)) {
        values['index'] = 0
        await update(values);
      } else {
        await add(values).then(res => {
          //跳转查看页
          router.push('/project/contract/view/' + res.id);
        });
      }
      createMessage.success({
        content: content,
        duration: 1,
      });
    }
    //删除
    function handleDeleteForm() {
      if (confirm("确认要删除吗")) {
        del(id.value).then(res => {
          router.push('/work/work-done');
        });
      }
    }


    function batchAdd(list) {
      //先删除
      selectedTypeList.value.forEach((_, index) => {
        removeSchemaByField([`contractAmount` + index]);
        removeSchemaByField([`contractRatio` + index]);
      });
      //后添加
      list.forEach((item, index) => {
        selectedTypeList.value.push({ name: item, code: index });
        appendSchemaByField(
          {
            field: `contractAmount` + index,
            component: 'Input',
            label: item + '：',
            required: true,
            componentProps: {
              type: 'number',
              placeholder: '请输入' + item + '金额',
            },
            colProps: {
              span: 24,
            },
          }, 'contractAmount',
        );
        appendSchemaByField(
          {
            field: `contractRatio` + index,
            component: 'Input',
            label: item + '(%)：',
            required: true,
            componentProps: {
              type: 'number',
              placeholder: '请输入' + item + '比例',
            },
            colProps: {
              span: 24,
            },
          }, 'contractRatio',
        );
      });

    }

    //主表单end

    return {
      onSearch2: useDebounceFn(onSearch2, 300), searchParams2, getAllPlan,
      handleSubmitForm, handleSaveForm, handleDeleteForm, registerForm, getTitle, handleSelectChange,
      getFlowData, serverData, id, type,
    };
  },
});
</script>
